package lesson10;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Demo_1003 {
    public static void main(String[] args) throws InterruptedException {
        counter counter=new counter();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.func();
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.func();
            }
        });
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(counter.counter);
    }
}


 class  counter{
    volatile int  counter=0;
     ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
     ReentrantReadWriteLock.ReadLock readLock= readWriteLock.readLock();
     ReentrantReadWriteLock.WriteLock writeLock=readWriteLock.writeLock();
    public  void func(){
//        readLock.lock();
//        counter++;
//        readLock.unlock();
        try {
            writeLock.lock();
            counter++;
        }finally {
            writeLock.unlock();
        }

    }
}
